/**
 * 
 */
package co.fitstart.admin.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.annotation.Dynamic;
import com.demo2do.core.support.Page;

import co.fitstart.admin.dao.CreditProductDao;
import co.fitstart.admin.service.CreditProductService;
import co.fitstart.entity.coupon.CreditCouponBatch;
import co.fitstart.entity.credit.product.CreditProduct;
import co.fitstart.entity.credit.product.CreditProductType;

/**
 * @author houtao
 *
 */
@Service("creditProductService")
public class CreditProductServiceImpl extends DataServiceImpl<CreditProduct> implements CreditProductService {
    
	@Dynamic
    private CreditProductDao creditProductDao;
	
    /* (non-Javadoc)
     * @see co.fitstart.admin.service.ecommerce.ProductService#list(co.fitstart.common.entity.ecommerce.product.ProductType, com.demo2do.core.web.resolver.Page)
     */
    public List<CreditProduct> list(CreditProductType type, Page page) {
        List<CreditProduct> result = creditProductDao.list(type, page.getBeginIndex(), page.getMaxResultRecords());
        page.calculate(result.size());
        return result.size() > page.getEveryPage() ? result.subList(0, page.getEveryPage()) : result;
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.ecommerce.ProductService#stick(co.fitstart.common.entity.ecommerce.product.Product, java.lang.String)
     */
    public void stick(CreditProduct product, CreditProductType type) {
        
        List<CreditProduct> sticks = creditProductDao.list(type);
        
        if(sticks.isEmpty()) {
            
            genericDaoSupport.update(product.stick(100));
            
        } else {
            
        	CreditProduct last = sticks.get(sticks.size() -1);
            genericDaoSupport.update(product.stick(last.getWeight()));
            
        }
        
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.ecommerce.ProductService#unStick(co.fitstart.common.entity.ecommerce.product.Product, java.lang.String)
     */
    public void unStick(CreditProduct product, CreditProductType type) {
        
        genericDaoSupport.update(product.unstick());
        
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.ecommerce.ProductService#create(co.fitstart.common.entity.ecommerce.product.Product)
     */
    public void create(CreditProduct product, Long operator) {
    	if(null != product.getCreditCouponBatchId()) {
    		CreditCouponBatch creditCouponBatch = genericDaoSupport.load(CreditCouponBatch.class, product.getCreditCouponBatchId());
    		genericDaoSupport.save(product.initCoupon(operator, creditCouponBatch));
    	}else {
    		 genericDaoSupport.save(product.initialize(operator));
    	}
    }
}
